<template>
	<el-header>
		<el-page-header :content="form.name" @back="onBack"></el-page-header>
		<div>
			<el-switch style="margin-right: 10px;" v-model="upgradeVersion" inactive-text="是否更新版本号"></el-switch>
			<el-button type="primary" @click="exportJson">提交</el-button>
		</div>
	</el-header>
	<el-main>
		<sc-workflow v-if="request" v-model="data" :dataList="dataList"></sc-workflow>
	</el-main>
</template>
<script setup>
import { ref, reactive, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import Api from '@/api/model/workflow.js'
import scWorkflow from '@/components/scWorkflow'
import { ElNotification } from 'element-plus';
import useTabs from '@/utils/useTabs'
const route = useRoute();
const router = useRouter()
const data = ref({
	"nodeName": "发起人",
	"type": 0,
	"id": "root",
	"formPerms": {},
	"nodeUserList": [],
	"childNode": {}
})
const form = ref({})
const dataList = ref([])
const request = ref(false)
const tipList = ref([])
const upgradeVersion = ref(true)
onMounted(() => {
	getInit()
})
const getInit = async () => {
	let param ={
		id:route.query.id,
		number:'flowDesign'
	}
	var res = await Api.process.detail.post(param);
	if (res.code == 200) {
		form.value = res.data
		if (res.data.process) {
			data.value = JSON.parse(res.data.process)
		}
		dataList.value = res.dataList
		request.value = true
	}
}
const onBack = () => {
	useTabs.close()
	router.back()
}
const exportJson = async () => {
	if (validate() == true) {
		let param = {
			bean: {
				id: form.value.id,
				process: JSON.stringify(data.value),
				upgradeVersion:upgradeVersion.value
			}

		}
		let res = await Api.process.saveFlow.post(param)
		if(res.code == 200){
			useTabs.close()
			router.back()
		}
	}
	else {
		ElNotification({ title: '验证失败', message: tipList.value.join(), type: 'warning' })

	}
}
const reErr = ({ childNode }) => {
	if (childNode) {
		let { type, error, nodeName, conditionNodes } = childNode;
		if (type == 1 || type == 2) {
			if (error) {
				tipList.value.push(nodeName + " 未设置人员");
			}
			reErr(childNode);
		} else if (type == 3) {
			reErr(childNode);
		} else if (type == 4) {
			reErr(childNode);
			for (var i = 0; i < conditionNodes.length; i++) {
				if (conditionNodes[i].error) {
					tipList.value.push('请设置' + conditionNodes[i].nodeName + '的条件');
				}
				reErr(conditionNodes[i]);
			}
		}
	} else {
		childNode = null;
	}
}
const validate = () => {
	tipList.value = [];

	if (data.value.childNode == undefined || data.value.childNode.id === undefined) {
		tipList.value = ['请完善流程节点']
	}
	reErr(data.value);
	if (tipList.value.length != 0) {
		return false
	}
	return true
}
</script>
